<template>
  <div class="parent">
    <!-- 侧边导航栏 -->
    <el-container>
      <el-aside :width="isCollapse? '70px' : '19vw'" :style="{'padding':isCollapse?'0':'0 1.5vw' }"> 
        <div class="title">
          <img :src="logo" alt="logo" class="logo" @click="toggleCollapse">
          <span v-show="!isCollapse">Trouble-Shooting</span>
        </div>
        <el-menu
          mode="vertical"
          :default-active="activeTab"
          @select="handleMenuSelect"
          :collapse="isCollapse"
          :collapse-stansition="false"
          class="side-menu"
          v-if="!isCollapse"
        >
          <el-menu-item index="repair">
            <img 
              src="../../assets/images/icon_maintenance.png" 
              class="menu-item-icon"
            >
            Repair Records
          </el-menu-item>
          <el-sub-menu index="analysis" v-if="auth===10">
            <template #title>
              <img src="../../assets/images/manage_icon_fault.png" class="menu-icon">
              Fault Statistics
            </template>
            <div class="item-border">
              <el-menu-item index="map-distribution">
                Map Distribution
              </el-menu-item>
              <el-menu-item index="user-distribution">
                User Distribution
              </el-menu-item>
              <el-menu-item index="fault-statistics">
                Fault Statistics
              </el-menu-item>
            </div>
          </el-sub-menu>
          <el-sub-menu index="admin">
            <template #title>
              <img src="../../assets/images/manage_icon_manage.png" class="menu-icon">
              Admin
            </template>
            <div class="item-border">
              <el-menu-item index="admin-list" v-if="auth===10">
                Admin List
              </el-menu-item>
              <el-menu-item index="instructions-list">
                Instructions
              </el-menu-item>
            </div>
          </el-sub-menu>
        </el-menu>

        <div class="collapse-button" @click="toggleCollapse">
          <el-icon>
            <component :is="isCollapse ? 'Expand' : 'Fold'"/>
          </el-icon>
        </div>

      </el-aside> 
    </el-container>


    <div class="right-container" :style="{ 'margin-left': isCollapse ? '70px' : '19vw' ,'width':isCollapse ? '97vw' : '81vw'}">
      <!-- 右侧头部内容 -->
      <div class="header">
        <span class="header-text">Welcome:{{ name }} </span>
        <el-button @click="confirmLogout()">Log out</el-button>
      </div>
      <!-- 右侧标签页内容 -->
      <div class="right-label">
        <div class="tab-container">
          <el-tabs 
            v-model="activeTab" 
            type="card" 
            closable 
            @tab-remove="handleTabRemove"
            @tab-click="handleTabClick" 
          >
            <el-tab-pane
              v-for="tab in tabs"
              :key="tab.name"
              :label="tab.title"
              :name="tab.name"
            >
            </el-tab-pane>
          </el-tabs>
        </div>

        <!-- 组件内容 -->
        <div class="show">
          <component 
            :is="currentComponent"
            @show-user-details="showUserDetails"
            @close-user-details="closeUserDetails"
            :user-details-data="userDetailsData"
          >
        </component>
        </div>
      </div>
      
      
    </div>
  </div>
</template>

<script setup>
  import { ref,  shallowRef,onMounted, computed } from 'vue';
  import { useRouter } from 'vue-router';
  import Repair from '../navLeft/Repair.vue';
  import MapView from '../navLeft/MapView.vue';
  import Overview from '../navLeft/Overview.vue';
  import Statistics from '../navLeft/Statistics.vue';
  import Admin from '../navLeft/Admin.vue';
  import Instructions from '../navLeft/Instructions.vue'
  import Userdetails from '../details/UserDetails.vue';
  import { ElMessageBox } from 'element-plus';
  import { useManageStore } from '../../store/manageStore';
  import { useSidebarStore } from '../../store/sidebarStore';

  const manageStore = useManageStore();
  const sidebarStore = useSidebarStore();
  const isCollapse = computed(() => sidebarStore.isCollapse);
  // 折叠状态
  const toggleCollapse = () => {
    sidebarStore.toggleCollapse();
  };
  // 标签页配置
  const TAB_CONFIG = {
    'repair': {
      title: 'Repair records',
      component: Repair
    },
    'map-distribution': {
      title: 'Map Distribution',
      component: MapView
    },
    'user-distribution': {
      title: 'User Distribution',
      component: Overview
    },
    'fault-statistics': {
      title: 'Fault Statistics',
      component: Statistics
    },
    'admin-list': {
      title: 'Admin List',
      component: Admin
    },
    'instructions-list': {
      title: 'Operation Instructions',
      component: Instructions
    }
  };
 
  const DEFAULT_TAB = 'repair';
  const router = useRouter();

  // 响应式数据
  const tabs = ref([]);
  const activeTab = ref(DEFAULT_TAB);
  const currentComponent = shallowRef(TAB_CONFIG[DEFAULT_TAB].component);
  const previousComponent = shallowRef(null);
  const userDetailsData = shallowRef(null);
  const name = computed(() => manageStore.name)
  const auth = computed(() => manageStore.auth)
  const logo = computed(() => manageStore.logo)
  const userId = computed(() => manageStore.userId)
  
  onMounted(() => {
    if(!userId.value) {
      router.push('/manageLogin')
    }
  })

  // 初始化第一个标签页
  if (tabs.value.length === 0) {
    addTab(DEFAULT_TAB);
  }

  // 添加标签页
  function addTab(tabName) {
    if (!TAB_CONFIG[tabName]) return;
    
    const exists = tabs.value.some(tab => tab.name === tabName);
    if (!exists) {
      tabs.value.push({
        name: tabName,
        title: TAB_CONFIG[tabName].title
      });
    }
    
    activeTab.value = tabName;
    currentComponent.value = TAB_CONFIG[tabName].component;
  }

  // 移除标签页
  function handleTabRemove(targetName) {
    const updatedTabs = tabs.value.filter(tab => tab.name !== targetName);
    
    if (activeTab.value === targetName) {
      const currentIndex = tabs.value.findIndex(tab => tab.name === targetName);
      const newActiveTab = tabs.value[currentIndex - 1]?.name ||   tabs.value[currentIndex + 1]?.name ||  DEFAULT_TAB;
      activeTab.value = newActiveTab;
      currentComponent.value = TAB_CONFIG[newActiveTab].component;
    }
    
    tabs.value = updatedTabs;
    
    if (tabs.value.length === 0) {
      addTab(DEFAULT_TAB);
    }
  }

  // 标签页点击事件
  function handleTabClick(tab) {
    const tabName = tab.props.name;
    currentComponent.value = TAB_CONFIG[tabName].component;
  }

  // 菜单选择处理
  function handleMenuSelect(tabName) {
    addTab(tabName);
  }
  // 退出登录
  function manageLogout() {
    router.push('/manageLogin');
  }
  //退出登录确认
  function confirmLogout() {
    ElMessageBox.confirm(
      'Are you sure you want to log out?',
      'Hint',
      {
        confirmButtonText:'confirm',
        cancelButtonText:'Cancel',
        type: 'warning',
        customClass: 'delete-confirm-box',
      }
    ).then(() => {
      manageLogout()
    }).catch(() => {

    })
  }
  
  //显示userdetails组件
  function showUserDetails(row) {
    previousComponent.value = currentComponent.value;
    currentComponent.value = Userdetails;
    userDetailsData.value = row;
  }

  //关闭userdetails组件
  function closeUserDetails() {
    currentComponent.value = previousComponent.value;
    previousComponent.value = null;
    userDetailsData.value = null;
  }
</script>

<style scoped>
  .parent {
    display: flex;
    width: 100vw;
    height: 100vh;
    background-color: white;
    color: black;
  }
  .el-container {
    height: 100vh;
    position: absolute; 
    background-color: rgb(245,245,245) !important;
  }
  :deep(.el-aside) {
    background: none !important;
    background-color: transparent !important;
  }
  :deep(.el-menu) {
    border-right: none !important;
    background: none !important;
    background-color: transparent !important;
  }
  .title {
    display: flex;
    align-items: center;
    font-size: 25px;
    height: 80px;
    border-bottom: 1px solid #ccc;
    margin-top: 15px;
    white-space: nowrap;/* 禁止换行 */
  }
  .item-border{
    margin-left: 40px;
    border-left: 1px solid gray;
  }
  .logo {
    width: 70px;
    height: 35px;
    margin-right: 5px;
    object-fit: contain;
  }
  .menu-item-icon{
    width: 36px;
    padding: 0 22px 0 0px;
  }
  .menu-icon {
    width: 30px;
    padding: 0 22px 0 8px;
  }
  /* 悬停或选中时切换为同一张图标 */
  .el-menu-item:hover .menu-item-icon,
  .el-menu-item.is-active .menu-item-icon {
    content: url('../../assets/images/icon_maintenance(white).png');
  }
  :deep(.el-sub-menu__title) {
    border-radius: 12px;
    font-size: 21px !important;
    height: 60px;
    margin: 5px 0;
  }
  :deep(.el-menu-item){
    margin: 8px 2px;
    border-radius: 12px;
    height: 58px; 
    font-size: 19px;
  }
  :deep(.el-menu-item:hover) {
    background-color:  rgb(3,52,145);
    color:#f5f7fa;
  }

  :deep(.el-sub-menu__title:hover) {
    border-radius: 10px;
  }
  :deep(.el-menu-item.is-active) {
    background-color: rgb(3,52,145);
    color:  #ecf5ff;
  }

  :deep(.el-sub-menu.is-active .el-sub-menu__title) {
    color: rgb(3,52,145);
  }
  .toggle-button {
    margin-bottom: 20px;
    position: absolute;
    height: 50px;
    bottom: 10px;
    left: 5px;
    border: 1px solid #ccc;
  }
  /* 新增折叠按钮样式 */
  .collapse-button {
    position: absolute;
    bottom: 20px;
    left: 0;
    width: 100%;
    height: 50px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    color: #666;
    background-color: #f5f5f5;
    border-top: 1px solid #e6e6e6;
    transition: all 0.3s;
    padding: 0 20px;
    box-sizing: border-box;
  }
  .collapse-button:hover {
    background-color: #e6e6e6;
    color: #333;
  }
  .collapse-button .el-icon {
    margin-right: 8px;
    font-size: 17px;
  }
  .collapse-button span {
    font-size: 13px;
    white-space: nowrap;
  }

  .right-container {
    position: absolute;
    height: 100%;
  }
  .header {
    position: relative;
    align-items: center;
    height: 65px;
    line-height: 65px;
    padding: 30px 20px 0 20px;
    background-color: rgba(250, 250, 250) !important;
  }
  .header-text {
    position: absolute;
    font-size: 23px;
    line-height: 55px;
    left: 60px;
    color: rgb(3,52,145);
  }
  .el-button {
    position: absolute;
    right: 100px;
    top: 60%;
    transform: translateY(-50%);
    font-size: 19px;
    width: 145px;
    height: 50px;
  }
  .right-label {
    position: relative;
    margin: 0 2vw;
  }
  .tab-container {
    align-items: center;
    padding: 10px 20px 0 20px;
  }
  :deep(.el-tabs) {
    font-size: 21px;
  }
  :deep(.el-tabs--card > .el-tabs__header) {
    margin: 0;
    height: 50px;
  }
  :deep(.el-tabs--card > .el-tabs__header .el-tabs__item) {
    height: 50px;
    width: 270px;
    line-height: 50px;
    font-size: 19px;
    padding: 0 20px;
    border-bottom: none;
    border-radius: 4px 4px 0 0;
  }
  :deep(.el-tabs--card > .el-tabs__header .el-tabs__item.is-active) { 
    border-bottom: 1px solid white;
    color: #409eff; 
  }

  .show {
    flex: 1;
    padding: 20px;
    overflow: auto;
    height: calc(100% - 120px);
    /* background-color: #f5f4f4; */
  }
</style>